﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpaceGame
{
    public class Keyboard : IInputDevice
    {
        public event EventHandler LeftPressed;

        public event EventHandler RightPressed;

        public event EventHandler UpPressed;

        public event EventHandler DownPressed;

        public event EventHandler ActionPressed;

        public void ProcessInput()
        {
            if (Console.KeyAvailable)
            {
                var keyInfo = Console.ReadKey(true);
                if (keyInfo.Key.Equals(ConsoleKey.A))
                {
                    OnLeftPressed();
                }

                if (keyInfo.Key.Equals(ConsoleKey.D))
                {
                    OnRightPressed();
                }

                if (keyInfo.Key.Equals(ConsoleKey.W))
                {
                    OnUpPressed();
                }

                if (keyInfo.Key.Equals(ConsoleKey.S))
                {
                    OnDownPressed();
                }

                if (keyInfo.Key.Equals(ConsoleKey.Spacebar))
                {
                    OnActionPressed();
                }
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);
                }
            }
        }

        protected virtual void OnLeftPressed() 
        {
            EventHandler handler = LeftPressed;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        protected virtual void OnRightPressed()
        {
            EventHandler handler = RightPressed;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        protected virtual void OnUpPressed()
        {
            EventHandler handler = UpPressed;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        protected virtual void OnDownPressed()
        {
            EventHandler handler = DownPressed;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        protected virtual void OnActionPressed()
        {
            EventHandler handler = ActionPressed;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }
    }
}
